<?php
/**
 * Created by PhpStorm.
 * User: CY
 * Date: 2018/3/26
 * Time: 13:05
 */

namespace app\api\model;


class Order extends BaseModel
{
    protected $hidden = ['user_id', 'delete_time', 'update_time'];
    protected $autoWriteTimestamp = true;

    /**
     * 订单快照信息
     * @param $value
     * @return mixed|null
     */
    public function getSnapItemsAttr($value){
        if(empty($value)){
            return null;
        }else{
            return json_decode($value);
        }
    }

    /**
     * 获取器 用户收货地址信息
     * @param $value
     * @return mixed|null
     */
    public function getSnapAddressAttr($value){
        if(empty($value)){
            return null;
        }else{
            return json_decode($value);
        }
    }

    /**
     * 根据用户id获得分页简要订单信息
     * @param $uid
     * @param int $page
     * @param int $size
     * @return \think\Paginator
     */
    public static function getSummaryByUser($uid, $page = 1, $size = 15) {
        $pagingData = self::where('user_id', '=', $uid)
            ->order('create_time desc')
            ->paginate($size, true, ['page' => $page]);
        return $pagingData;
    }

    /**
     * 分页获取简要订单信息
     * @param int $page
     * @param int $size
     * @return \think\Paginator
     */
    public static function getSummaryByPage($page = 1,$size = 20){
        $pagingData = self::order('create_time desc')->paginate($size,true,['page' => $page]);
        return $pagingData;
    }

    /**
     * 获取订单相关联的商品
     * @return \think\model\relation\BelongsToMany
     */
    public function products(){
        return $this->belongsToMany('Product','order_product','product_id','order_id');
    }
}